package com.googlecode.sere.connectors

import httpcomponents.HttpCoreRequest
import javax.servlet.http.HttpServletRequest
import com.googlecode.sere.http._
import com.googlecode.sere.util.Implicits._
import org.apache.http.message.BasicHeaderValueParser

class ServletHttpRequest(private val impl: HttpServletRequest) extends HttpRequest {

  lazy val method = impl.getMethod.toLowerCase

  lazy val contextPath = impl.getContextPath + impl.getServletPath

  lazy val uri = {
    val rta = new StringBuilder()
    rta ++ impl.getRequestURI
    val qs = impl.getQueryString
    if (qs != null)
      rta ++ "?" ++ qs

    rta.toString
  }

  lazy val body = new String(impl.getInputStream.slurp)

  def headerElements(name: String): Seq[HeaderElement] = {
    val headers = impl.getHeaders(name).toSeq map { _.asInstanceOf[String] }
    val elements = headers map { line =>
      val apacheHeader = BasicHeaderValueParser.parseElements(line , null)
      HttpCoreRequest.apacheHeaderToSereHeader(apacheHeader)
    }
    elements.flatten
  }
}
